package com.jackaltsc.mydemodatastorage.sharedpreferences;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;

import com.jackaltsc.mydemodatastorage.R;

/**
 * 存储方式一 简单键值对
 */
public class SharedPreActivity extends Activity {

    SharedPreferences sp;
    SharedPreferences.Editor spEditor;

    private static final String FILE_USER = "FILE_USER_LO";
    private static final String KEY_KEEP = "keeppswd";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_USERPASSWD = "userpswd";

    private EditText etUserName, etUserPasswd;
    private Button btnLogin;
    private CheckBox cbKeep;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_preferences);

        initView();
        initData();
    }

    private void initView() {
        etUserName = (EditText) findViewById(R.id.et_username);
        etUserPasswd = (EditText) findViewById(R.id.et_userpasswd);
        cbKeep = (CheckBox) findViewById(R.id.cb_keep);
        btnLogin = (Button) findViewById(R.id.btn_login);
    }

    //初始化数据
    private void initData() {

        sp = getSharedPreferences(FILE_USER, Context.MODE_PRIVATE);

        //获取之前是否点击了保存密码
        cbKeep.setChecked(sp.getBoolean(KEY_KEEP, false));

        //如果点击了就获取密码
        if (cbKeep.isChecked()) {
            etUserName.setText(sp.getString(KEY_USERNAME, ""));
            etUserPasswd.setText(sp.getString(KEY_USERPASSWD, ""));
        }

        btnLogin.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                String userName = etUserName.getText().toString().trim();
                String userPasswd = etUserPasswd.getText().toString().trim();

                if (cbKeep.isChecked()) {
                    funDataSave(userName, userPasswd, 1);
                } else {
                    funDataSave(userName, userPasswd, 0);
                }
            }
        });
    }

    private void funDataSave(String username, String userpassword, int type) {

        spEditor = sp.edit();

        if (type == 0) {

            spEditor.putBoolean(KEY_KEEP, false);
            spEditor.putString(KEY_USERNAME, "");
            spEditor.putString(KEY_USERPASSWD, "");
        } else {
            spEditor.putBoolean(KEY_KEEP, true);
            spEditor.putString(KEY_USERNAME, username);
            spEditor.putString(KEY_USERPASSWD, userpassword);
        }
        spEditor.apply();
    }
}
